/*
 * Copyright (c) 2006 - 2022, webrx.cn All rights reserved.
 *
 */
package cn.webrx;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>Project: app2022 - Ex8
 * <p>Powered by webrx On 2022-01-19 09:25:47
 *
 * @author webrx [webrx@126.com]
 * @version 1.0
 * @since 17
 */
public class Ex8 {
    public static void main(String[] args) {
        String f = "p.jpg";
        System.out.println(head(f));
        System.out.println(head("m.jpg"));
        System.out.println(head("ok.png"));
        System.out.println(head("d:\\w.zip"));
        System.out.println(head("d:\\File3.zip"));

        System.out.println(ext("d:\\my.exe"));
    }

    public static String ext(String file) {
        String ext = "未知";
        Map<String, String> map = new HashMap<>();
        map.put("ffd8ffe0", "jpg");
        map.put("504b0304", "zip");
        map.put("89504e47", "png");

        String head = head(file);
        head = head.substring(0, head.lastIndexOf(":"));
        if (map.containsKey(head)) {
            ext = map.get(head);
        } else {
            ext = "未知类型";
        }
        return ext;
    }


    /**
     * Description: 获取文件的头信息
     *
     * @date: 2022/1/19 9:31
     * @params: [java.lang.String]
     * @return: java.lang.String
     */
    public static String head(String file) {
        return head(new File(file));
    }

    /**
     * Description:  获取文件的头信息
     *
     * @date: 2022/1/19 9:30
     * @params: [java.io.File]
     * @return: java.lang.String
     */
    public static String head(File file) {
        String info = "未知";
        try (var f = new FileInputStream(file)) {
            byte[] buf = new byte[4];
            f.read(buf);
            StringBuilder sbu = new StringBuilder();
            for (byte b : buf) {
                sbu.append(String.format("%02x", b));
            }
            String filename = file.getName();
            String ext = filename.lastIndexOf(".") != -1 ? filename.substring(filename.lastIndexOf(".") + 1) : "unknow";
            info = sbu + ":" + ext;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return info;
    }
}
